const express = require('express');
const path = require('path');
const fs = require('fs');
const time = require('time-stamp');
const app = express();
const formidable = require('formidable');

app.listen(3000, () => {
  console.log('服务器已开启')
});
const router = express.Router();

//读取文件
let data = JSON.parse(fs.readFileSync(path.join(__dirname, 'persons.json')))

app.use(express.urlencoded({
  extended: false
}))

app.use(express.static(path.join(__dirname, '../view')))
//渲染register
app.get('/register', (req, res) => {
  res.sendFile(path.join(__dirname, '../view/register.html'))
})

//注册
app.post('/register', (req, res, next) => {
  let lalala = formidable({
    uploadDir: path.join(__dirname, 'file'),
    keepExtensions: true //是否保留上传后文件的后缀
  })
  lalala.parse(req, (err, fileds, files) => {

    let oldpath = files.photo.filepath;
   
    let {
      username,
      password,
      password2
    } = fileds;
    if (!username || !password || !password2) {
      next("请输入有效内容")
      fs.unlinkSync(oldpath)
      return
    }
    if (password != password2) {
      next("两次密码不一致")
      fs.unlinkSync(oldpath)
      return
    }
    let a = data.find(item => {
      return username == item.username
    })
    if (a) {
      res.send('用户名已存在')
      fs.unlinkSync(oldpath)
      return
    }
    if (err) {
      res.send(err)
      return
    }
    let newpath = path.join(__dirname, 'file', files.photo.originalFilename);
    fs.renameSync(oldpath, newpath)

    let s = "/file/" + files.photo.originalFilename
    data.push({
      username,
      password,
      time: req.time,
      url: s
    })
    fs.writeFileSync(path.join(__dirname, "persons.json"), JSON.stringify(data))
    res.send("注册成功")
  })

})
module.exports = router;